package com.cxhome.cxinfox.cxrole;

import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.traffic.managent.base.BaseService;
import com.traffic.managent.base.Paginator;
import com.traffic.managent.model.system.Role;
import com.traffic.managent.util.SQLUtils;
import com.traffic.managent.util.StringUtils;
import com.traffic.managent.util.UtilsUtils;

public class RoleService extends BaseService {
	private static Logger log = Logger.getLogger(RoleService.class);
	public static final RoleService service = new RoleService();

	
	public Page<Role> paginate(Role model, Paginator paginate, StringBuilder orderSql) {

		SQLUtils sql = new SQLUtils(" from cx_role t where 1=1 ");
		if (model.getAttrValues().length != 0) {
			sql.setAlias("t");
			// 查询条件
			sql.whereLike("names", model.getStr("names"));
		}
		return Role.dao.paginate(paginate, "select t.* ", sql.toString());
	}
	
	/**
	 * 角色下拉框
	 * 
	 * @return
	 */
	public String selectRole(String selected) {

		List<Role> list = Role.dao.find(" select ids,names from cx_role where 1=1  order by orderids desc ");

		StringBuffer sb = new StringBuffer("");

		if (list != null && list.size() > 0) {
			for (Role role : list) {
				sb.append("<option value=\"");
				sb.append(role.getStr("ids"));
				sb.append("\" ");
				sb.append((selected != null && role.getStr("ids").equals(selected)) ? "selected" : "");
				sb.append(">");
				sb.append(role.getStr("names"));
				sb.append("</option>");
			}
		}
		return sb.toString();
	}

	/**
	 *根据roleids获取功能功能ids
	 * @param roleid
	 * @return
	 */
	public String getOperatoridsByRoleid(String roleid) {
		String sql = " select operatorids as menus from cx_role where ids = ?";
		Record record = Db.findFirst(sql, roleid);
		String menus = record.getStr("menus").replaceAll("operator_", "");
		return menus;
	}

	/**
	 * 保存授权信息
	 * 
	 * 
	 * @param roleid
	 * @param menus
	 */
	public void saveAuth(String roleid, String menus, String update_id) {

		if (StringUtils.isNotEmpty(menus)) {
			Db.update("update cx_role set operatorids = ? where ids = ? ", menus, roleid);
		}
	}

	/**
	 * 更新或者新增
	 */
	public void saveOrUpdate(String ids, Role model) {
		if (!"".equals(ids) && ids != null) { // 更新
			model.update();
		} else { // 新增
			String nowids = UtilsUtils.getRandomId(30);
			model.put("ids", nowids);
			model.put("paths", model.getStr("parentids") + "/" + nowids);
			model.save();
		}
	}
	
	
	
}
